<template>
	<div style="padding-bottom: 40px;">
		<div class="fixed-header">
			<van-sticky>
				<div class="topdropdown">
					<van-dropdown-menu>
						<van-dropdown-item v-model="searchObj.value1" :options="option1" title="状态"
							@change="statusChange" />
						<van-dropdown-item v-model="params.storeId" :options="option2" title="店铺"
							@change="storeChange" />
					</van-dropdown-menu>
					<div class="dropdownLeft" v-if="searchObj.value1"></div>
					<div class="dropdownRight" v-if="params.storeId"></div>
				</div>
				<div class="searchBox">
					<van-search v-model="params.name" :placeholder="placeholder" @search="handleSearch">
						<template #right-icon>
							<div class="search-confirm" @click.stop="handleSearch">
								<span style="margin-right: 10px;height: 24px;">|</span>
								<span class="search-text">搜索</span>
							</div>
						</template>
					</van-search>
				</div>
			</van-sticky>
		</div>
		<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
			<van-list v-model:loading="loading" v-model:error="error" error-text="请求失败，点击重新加载" finished-text="没有更多数据了"
				:finished="finished" @load="getdata">
				<DeviceList :list="list" :mark="mark" @AddressEdit="updateXinxi" @disableswAccount="updateDiaable">
				</DeviceList>
			</van-list>
		</van-pull-refresh>
		<div class="footer" v-if=" Identity == 1 ">
			<van-button type="primary" round style="width: 100%;" to="/secondaryAccountAdd">添加子账号</van-button>
		</div>
		<!-- 解禁||禁用 -->
		<van-dialog v-model:show="disableshow" title="提示" show-cancel-button :keyboard-enabled="false"
			@confirm="dialogConfirm">
			<div class="prompt">{{ disableTitle }}</div>
		</van-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
	} from "vue";
	import {
		getUserid,
		getIdentity
	} from '@/utils/auth';
	import {
		deviceUsersList,
		deviceUsersUnBan,
		deviceUsersBanJunior
	} from '@/api/deviceUsers';
	import {
		showToast
	} from 'vant';
	import {
		useRouter
	} from 'vue-router';
	import {
		StoresList
	} from '@/api/deviceRechargeConfig';
	const router = useRouter();

	const mark = ref('secondaryAccount');
	const placeholder = ref('请输入账号/名称搜索');
	const option1 = [{
		text: '全部',
		value: ''
	}, {
		text: '正常',
		value: 1
	}, {
		text: '黑名单',
		value: 2
	}];

	var option2 = reactive([]);

	const searchObj = ref({
		value1: '',
		value2: 0,
		searchValue: undefined
	});


	const loading = ref(false);

	const finished = ref(false);
	const error = ref(false);
	// 下拉刷新状态
	const refreshing = ref(false);
	const params = ref({
		size: 10,
		pages: 1,
		userId: getUserid(),
		status: '',
		storeId: '',
		name: '',
	});
	const list = reactive([]);
	const Identity = getIdentity();
	onMounted(() => {
		getstore();
		getdata();
	});
	// 下拉筛选商店
	const storeChange = () => {
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	const statusChange = (type) => {
		if (type == 1) {
			params.value.status = 0;
		} else if (type == 2) {
			params.value.status = 1;
		} else {
			params.value.status = '';
		}
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 商店下拉列表
	const getstore = async () => {
		const userId = {
			userId: getUserid(),
		}
		try {
			const response = await StoresList(userId);
			const records = response.data || [];
			option2 = [{
					text: "全部",
					value: ''
				}, // 插入的选项
				...records.map((item, index) => ({ // 展开原数组
					text: item.storeName,
					value: item.id,
				}))
			];
		} catch (err) {
			//console.error('获取数据失败', err);
		}
	}
	const getdata = async (isRefresh = false) => {
		loading.value = false;
		try {
			// 防止重复请求
			if (loading.value && !isRefresh) return;
			// 重置错误状态
			error.value = false;
			// 设置加载状态
			loading.value = true;

			const response = await deviceUsersList(params.value);
			const records = response.data.records || [];

			// 如果是刷新操作，替换而不是追加数据
			if (isRefresh) {
				list.splice(0, list.length, ...records);
			} else {
				list.push(...records);
			}

			// 更新分页状态
			finished.value = records.length < params.value.size;
			params.value.pages += 1;
		} catch (err) {
			//console.error('获取数据失败', err);
			error.value = true;
			finished.value = false; // 确保可以重试

			// 如果是刷新操作需要保留刷新状态
			if (!isRefresh) {
				refreshing.value = false;
			}
		} finally {
			loading.value = false;
			// 如果是刷新操作，需要特殊处理
			if (isRefresh) {
				refreshing.value = false;
			}
		}
	};
	// 下拉刷新处理
	const onRefresh = () => {
		// 立即清空列表
		list.splice(0, list.length);

		// 重置分页参数
		params.value.pages = 1;
		params.value.name = '';
		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 输入框搜索
	const handleSearch = (item) => {
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		// 重置状态
		finished.value = false;
		loading.value = false;
		error.value = false;
		getdata(true);
	};

	const updateXinxi = (item) => {
		let storeIds = item.storeIds || [];
		if (Identity == 0) {
			showToast('请先完成商户审核再编辑子账户');
		} else if (Identity == 1) {
			router.push({
				name: 'secondaryAccountUpdate',
				params: {
					id: item.id,
					storeIds: JSON.stringify(storeIds)
					// storeIds: JSON.stringify(item.storeIds)
				}
			})
		} else {
			showToast('二级账号无编辑子账户权限');
		}
	};


	const disableshow = ref(false);
	const disableTitle = ref('');
	const disableStatus = ref('');
	const disableId = ref('');
	const updateDiaable = (item) => {
		disableStatus.value = item.status;
		disableId.value = item.id;
		if (item.status) {
			disableTitle.value = '您确定要启用该账号吗?'
		} else {
			disableTitle.value = '您确定要禁用该账号吗?'
		}
		if (Identity == 0) {
			showToast('请先完成商户审核再编辑子账户');
		} else if (Identity == 1) {
			disableshow.value = true;
		} else {
			showToast('二级账号无编辑子账户权限');
		}
	};
	const dialogConfirm = async () => {
		var params = {
			id: disableId.value
		}
		if (disableStatus.value) {
			try {
				const response = await deviceUsersUnBan(params);
				if (response.status == 200) {
					showToast({
						type: 'success',
						message: '启用成功',
						forbidClick: true,
						duration: 1000
					});
					setTimeout(() => {
						onRefresh();
					}, 1000)
				} else {
					showToast({
						type: 'fail',
						message: response.desc || '启用失败',
						forbidClick: true,
						duration: 1000
					});
				}
			} catch (err) {
				showToast({
					type: 'fail',
					message: err.desc || '启用失败',
					forbidClick: true,
					duration: 1000
				});
			}
		} else {
			try {
				const response = await deviceUsersBanJunior(params);
				if (response.status == 200) {
					showToast({
						type: 'success',
						message: '禁用成功',
						forbidClick: true,
						duration: 1000
					});
					setTimeout(() => {
						onRefresh();
					}, 1000)
				} else {
					showToast({
						type: 'fail',
						message: response.desc || '禁用失败',
						forbidClick: true,
						duration: 1000
					});
				}
			} catch (err) {
				showToast({
					type: 'fail',
					message: err.desc || '禁用失败',
					forbidClick: true,
					duration: 1000
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	:deep(.van-dropdown-menu__bar) {
		box-shadow: none;

		.van-dropdown-menu__title {
			color: orange;
		}

		.van-dropdown-menu__title:after {
			border-color: transparent transparent orange orange;
		}
	}

	:deep(.searchBox) {
		.van-search {
			background-color: white;

			// 搜索框
			.van-search__content {
				background-color: white;
				border: 1px solid #cccccc;
				// border-radius: 5px;
				background-color: #f5f5f5;
			}
		}

		.van-search__action {
			color: #fff;
			background-color: #2FBC3C;
			border-radius: 16px;
			width: 40px;
			text-align: center;
			margin: 0 10px;
		}

		// 文字
		.search-confirm {
			display: flex;
			align-items: center;
			height: 100%;
			padding: 0 12px;

			.search-text {
				color: rgb(81, 164, 208);
				/* 蓝色搜索文字 */
				font-size: 14px;
				font-weight: 500;
				white-space: nowrap;
				cursor: pointer;
			}
		}
	}

	.topdropdown {
		position: relative;

		.dropdownLeft {
			position: absolute;
			bottom: 0;
			left: 16%;
			width: 20%;
			height: 3px;
			background-color: orange;
		}

		.dropdownRight {
			position: absolute;
			bottom: 0;
			right: 14%;
			width: 20%;
			height: 3px;
			background-color: orange;
		}
	}

	.prompt {
		margin: 8px 0;
		text-align: center;
	}

	.footer {
		position: fixed;
		bottom: 42px;
		z-index: 2;
		// background-color: #FFF;
		height: 66px;
		width: 100%;
		padding: 10px;
		box-sizing: border-box;
	}
</style>